#!/bin/sh
########################################################################
# Begin $rc_base/init.d/network
#
# Description : Network Control Script
#
# Authors     : Michael Tremer - mitch@ipfire.org
#
# Version     : 01.00
#
# Notes       : Written for IPFire by its team
#
########################################################################

. /etc/sysconfig/rc
. ${rc_functions}
eval $(/usr/local/bin/readhash /var/ipfire/ethernet/settings)

init_networking() {
	/etc/rc.d/init.d/dnsmasq start
}

DO="${1}"
shift

if [ -n "${1}" ]; then
	ALL=0
	for i in green red blue orange; do
		eval "${i}=0"
	done
else
	ALL=1
	for i in green red blue orange; do
		eval "${i}=1"
	done
fi

while [ ! $# = 0 ]; do
	for i in green red blue orange; do
		if [ "${i}" == "${1}" ]; then
			eval "${i}=1"
			shift
		fi
	done
done

case "${DO}" in
	start)
		[ "${ALL}" == "1" ] && init_networking

		# Starting interfaces...
		# GREEN
		[ "$green" == "1" ] && /etc/rc.d/init.d/networking/green start

		# BLUE
		[ "$blue" == "1" ] && [ "$CONFIG_TYPE" = "3" -o "$CONFIG_TYPE" = "4" ] && \
			/etc/rc.d/init.d/networking/blue start

		# ORANGE
		[ "$orange" == "1" ] && [ "$CONFIG_TYPE" = "2" -o "$CONFIG_TYPE" = "4" ] && \
			/etc/rc.d/init.d/networking/orange start

		# RED
		if [ "$red" == "1" ]; then
			if [ "$CONFIG_TYPE" = "1" -o "$CONFIG_TYPE" = "2" -o "$CONFIG_TYPE" = "3" -o "$CONFIG_TYPE" = "4" ]; then
				# Remove possible leftover files
				rm -f /var/ipfire/red/{active,device,dial-on-demand,dns1,dns2,local-ipaddress,remote-ipaddress,resolv.conf}
				[ "$AUTOCONNECT" == "off" ] || /etc/rc.d/init.d/networking/red start
			fi
		fi

		/etc/rc.d/init.d/static-routes start
		;;

	stop)
		# Stopping interfaces...
		# GREEN
		[ "$green" == "1" ] && /etc/rc.d/init.d/networking/green stop

		# BLUE
		[ "$blue" == "1" ] && [ "$CONFIG_TYPE" = "3" -o "$CONFIG_TYPE" = "4" ] && \
			/etc/rc.d/init.d/networking/blue stop

		# ORANGE
		[ "$orange" == "1" ] && [ "$CONFIG_TYPE" = "2" -o "$CONFIG_TYPE" = "4" ] && \
			/etc/rc.d/init.d/networking/orange stop

		# RED
		if [ "$red" == "1" ]; then
			if [ "$CONFIG_TYPE" = "1" -o "$CONFIG_TYPE" = "2" -o "$CONFIG_TYPE" = "3" -o "$CONFIG_TYPE" = "4" ]; then
				/etc/rc.d/init.d/networking/red stop
			fi
		fi

		# Stopping dnsmasq if network all networks shutdown
		[ "${ALL}" == "1" ] && /etc/rc.d/init.d/dnsmasq stop

		exit 0
		;;

	restart)
		for i in green red blue orange; do
			if [ "${!i}" == "1" ]; then
				ARGS+=" ${i}"
			fi
		done
		${0} stop ${ARGS}
		sleep 1
		${0} start ${ARGS}
		;;

	*)
		echo "Usage: ${0} {start|stop|restart} [device(s)]"
		exit 1
		;;
esac

# End /etc/rc.d/init.d/network
